package cn.mybatis;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import cn.mybatis.school.PageNo;
import cn.mybatis.school.Subject;

public class MyBatisTest {

	public static void main(String[] args) throws Exception {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);// 读取配置文件

		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 启动驱动

		SqlSession session = sqlSessionFactory.openSession(false);// 关闭事物自动提交
		int r = 0;
		try {
			SubjectDao dao = session.getMapper(SubjectDao.class); // 相当于statement 执行SQL语句

			System.out.println(dao.getClass().getName());

			// 查询
//			List<Subject> list = dao.findAll();
//			for (Subject sb : list) {
//				System.out.println(sb);
//			}
			// 增加
//			Subject s = new Subject();
//			s.setGradeid(14);
//			s.setClasshour(5);
//			s.setSubjectname("mybatis精讲");
//			r = dao.add(s);
//			System.out.println(r > 0 ? "成功" : "失败");

			// 删除
//			r = dao.del(76L);
//			System.out.println(r > 0 ? "成功" : "失败");

//			// 修改

//			r = dao.update(56L, 75L);
//			System.out.println(r > 0 ? "成功" : "失败");

//			2(选做):完成Subject的分页操作
//			 方法类似：
//			 List paging(int pageNo,int pageSize)
			System.out.println("分页查询");
			PageNo p = new PageNo();
			p.setPagaNo((p.getPagaNo() - 1) * p.getPageSize());

			List<Subject> list1 = dao.paging(p);
			for (Subject sb : list1) {
				System.out.println(sb);
			}

			session.commit();
		} finally {
			session.close();
		}
	}

}
